<script setup lang="ts">
import { computed, nextTick, reactive, ref, useTemplateRef } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit } from "@element-plus/icons-vue";
import { isMobile, NetState, Operation } from "@/utils/utils.ts";
import {
  addClasses,
  delClasses,
  updateClasses,
  getClassList
} from "@/api/classes";
import { cloneDeep } from "@pureadmin/utils";
import dayjs from "dayjs";

const classList = ref([]);
const dialogVisible = ref(false);
const submitLoading = ref(false);
const editFormRef = useTemplateRef("editFormRef");
const curOperate = ref(Operation.Create);
const editForm = ref({
  class_name: "",
  grade: "",
  department: "",
  teacher_name: "",
  enrollment_year: ""
});
const editFormRules = reactive({
  class_name: [
    { required: true, message: "请输入班级名称", trigger: "blur" },
    { max: 50, message: "最多50个字符", trigger: "blur" }
  ],
  grade: [{ max: 20, message: "最多20个字符", trigger: "blur" }],
  department: [{ max: 20, message: "最多50个字符", trigger: "blur" }],
  teacher_name: [{ max: 50, message: "最多50个字符", trigger: "blur" }]
});

const dialogTitle = computed(() => {
  return curOperate.value === Operation.Create ? "添加班级" : "修改班级";
});

const openDialog = async function (operate: Operation, row?: object) {
  await nextTick();
  editFormRef.value?.clearValidate();
  curOperate.value = operate;
  editForm.value = operate === Operation.Create ? {} : cloneDeep(row);
  dialogVisible.value = true;
};
const submitHandle = async function () {
  await editFormRef.value.validate(valid => {
    if (!valid) return;
    const param = {
      ...editForm.value
    };
    submitLoading.value = true;

    const api = {
      [Operation.Create]: addClasses,
      [Operation.Update]: updateClasses
    };
    api[curOperate.value]?.(param)
      .then(res => {
        if (res.code === NetState.Success) {
          const msg =
            curOperate.value === Operation.Create
              ? "班级添加成功"
              : "班级修改成功";
          ElMessage.success(msg);
          dialogVisible.value = false;
          getClassesList();
        }
        submitLoading.value = false;
      })
      .catch(() => {
        submitLoading.value = false;
      });
  });
};

const getClassesList = async function () {
  const result = await getClassList();
  const list = result.data ?? [];
  list.forEach(item => {
    item.enrollment_year = item.enrollment_year
      ? dayjs(item.enrollment_year).format("YYYY")
      : "";
    item.create_time = dayjs(item.create_time).format("YYYY-MM-DD hh:mm");
  });
  classList.value = list;
};
getClassesList();

const delClass = function (item) {
  ElMessageBox.confirm(
    `删除班级“${item.class_name}”则该班级的学生也会被删除，是否确认删除？`,
    {
      title: "确认删除",
      type: "warning"
    }
  )
    .then(() => {
      const params = {
        class_id: item.class_id
      };
      return delClasses(params);
    })
    .then(res => {
      if (res.code === NetState.Success) {
        ElMessage.success(`班级“${item.class_name}”已删除`);
        getClassesList();
      }
    });
};
</script>

<template>
  <div class="page-container">
    <ElButton type="primary" @click="openDialog(Operation.Create)"
      >添加班级</ElButton
    >
    <div class="table-box">
      <ElTable :data="classList">
        <ElTableColumn
          label="班级名称"
          prop="class_name"
          min-width="140"
          fixed="left"
          show-overflow-tooltip
        />
        <ElTableColumn label="学生人数" prop="stu_number"></ElTableColumn>
        <ElTableColumn label="年级" prop="grade" />
        <ElTableColumn
          label="教师名称"
          prop="teacher_name"
          show-overflow-tooltip
        />
        <ElTableColumn
          label="所属院系"
          prop="department"
          show-overflow-tooltip
        />
        <ElTableColumn
          label="入学年份"
          prop="enrollment_year"
          min-width="100"
        />
        <ElTableColumn label="创建时间" prop="create_time" min-width="150" />
        <ElTableColumn label="操作" width="70" align="center" fixed="right">
          <template #default="{ row }">
            <ElButton
              class="btn"
              :icon="Edit"
              @click="openDialog(Operation.Update, row)"
              text
            ></ElButton>
            <ElButton
              class="btn"
              :icon="Delete"
              @click="delClass(row)"
              text
            ></ElButton>
          </template>
        </ElTableColumn>
        <template #empty>
          <ElEmpty />
        </template>
      </ElTable>
    </div>

    <ElDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="520"
      :close-on-click-modal="false"
      :fullscreen="isMobile()"
    >
      <div class="dialog-form">
        <ElForm
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="80"
        >
          <ElFormItem label="班级名称" prop="class_name">
            <ElInput
              v-model.trim="editForm.class_name"
              placeholder="请输入班级名称"
            />
          </ElFormItem>
          <ElFormItem label="年级" prop="grade">
            <ElInput v-model.trim="editForm.grade" placeholder="请输入年级" />
          </ElFormItem>
          <ElFormItem label="所属院系" prop="department">
            <ElInput
              v-model.trim="editForm.department"
              placeholder="请输入所属院系"
            />
          </ElFormItem>
          <ElFormItem label="教师名称" prop="teacher_name">
            <ElInput
              v-model.trim="editForm.teacher_name"
              placeholder="请输入教师名称"
            />
          </ElFormItem>
          <ElFormItem label="入学年份" prop="enrollment_year">
            <ElDatePicker
              v-model="editForm.enrollment_year"
              type="year"
              placeholder="请选择入学年份"
            />
          </ElFormItem>
        </ElForm>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <div class="dialog-form-tips">
            <span class="star">*</span> 为必填项
          </div>
          <ElButton @click="dialogVisible = false">取消</ElButton>
          <ElButton
            type="primary"
            @click="submitHandle"
            :loading="submitLoading"
          >
            确定
          </ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.page-container {
  .btn {
    padding: 0;
  }

  .table-box {
    margin-top: 20px;
    overflow: hidden;
  }
}
</style>
